package com.atguigu.gulimall.product.sync.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadDemo2 {
    public static void main(String[] args) {
      Share share = new Share();
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                share.add();
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                share.sub();
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                share.add();
            }
        }, "CC").start();

        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                share.sub();
            }
        }, "DD").start();
    }
}

class Share {
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void add() {
        try {
            lock.lock();
            while (number != 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "::" + number);
            condition.signalAll();
        } finally {
            lock.unlock();
        }

    }

    public void sub(){
        try {
            lock.lock();
            while (number != 1) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "::" + number);
            condition.signalAll();
        } finally {
            lock.unlock();
        }

    }

}